<template>
	<view class="centem-body">

		<!-- 全屏加载 -->
		<cover-bulr-bg v-if="coverBulr"></cover-bulr-bg>

		<!-- 自定义状态栏 -->
		<view class="nav-view">
			<view class="nav-icon" :style="{'margin-top':statusBarHeight + 'px'}" @tap="tarBlack()">
				<image class="fengrui-img" src="../../static/data/back-icon.svg" mode="aspectFit"></image>
			</view>
		</view>

		<!-- 密码访问 -->
		<block v-if="protected">
			<common-pass @passTap="emitPass" :isError="isError" :getPass="getPass" :public_name="wxSet.public_name"
				:public_key="wallInfo.public_key" :public_step="public_step"
				style="margin-top: 280rpx;display: block;"></common-pass>
		</block>

		<block v-else>
			<!-- 滚动案例区 -->
			<swiper class="swiper-wall" easing-function="easeInOutCubic" :current="swipreIndex" @change="bindChange"
				:next-margin="imgUrls.length > 1 ? '30px':'0px'" :previous-margin="imgUrls.length > 1 ? '30px':'0px'">
				<block v-for="(item ,index) in imgUrls" :key="index">
					<swiper-item class="swiper-wall-item">
						<view class="swiper-wall-list-img">
							<!-- 图片 -->
							<image :src="item" class="fengrui-img-wall" mode="widthFix" />
						</view>
					</swiper-item>
				</block>
			</swiper>

			<!-- 背景 -->
			<view class="wall-bg-left"></view>
			<view class="wall-bg-right"></view>

			<!-- 下载组建 -->
			<view class="wall-flex">
				<button class="" open-type="share">
					<view class="wall-radus wall-share">
						<image class="wall-radus-img" src="../../static/data/share.svg" mode=""></image>
					</view>
					<view class="wall-radus-font">
						分享好友
					</view>
				</button>
				<button class="" v-if="wallInfo.fr_down_url != ''" @tap="sevePhto('zip')">
					<view class="wall-radus wall-url">
						<image class="wall-radus-img"
							:src="isShow ?'/static/data/ad_video.svg':'../../static/data/Appendixes.svg'" mode="">
						</image>
					</view>
					<view class="wall-radus-font">
						{{isShow ?'网上打包':'打包保存' }}
					</view>
				</button>
				<button class="" @tap="sevePhto('img')" v-if="wallInfo.pos_read == '6'">
					<view class="wall-radus wall-down">
						<image class="wall-radus-img"
							:src="isShow ? '/static/data/ad_video.svg' : '../../static/data/wx_video_icon.svg'" mode="">
						</image>
					</view>
					<view class="wall-radus-font">
						{{isShow?'获取封面':'获取封面' }}
					</view>
				</button>
				<button class="" @tap="sevePhto('img')" v-if="wallInfo.pos_read == '5'">
					<view class="wall-radus wall-down">
						<image class="wall-radus-img"
							:src="isShow ? '/static/data/ad_video.svg' : '../../static/data/down.svg'" mode="">
						</image>
					</view>
					<view class="wall-radus-font">
						{{isShow?'保存壁纸':'保存壁纸' }}
					</view>
				</button>
			</view>

			<!-- 弹窗 -->
			<view class="privacy-bg" v-if="showPrivacy">
				<view class="privacy-view">
					<view class="privacy-title">打包保存</view>
					<block v-for="(item, index) in  wallInfo.fr_down_url" :key="index">
						<view class="privac-text">
							<text user-select="true" style="word-break: break-all;">
								{{code64 == '' ? item : code64 }}
							</text>
						</view>
						<view class="privac-btn" v-if="code64 != '' " @tap="tapDownUrl(item)">复制Resource值</view>
					</block>
					<view class="privac-x" @tap="noPrivacy()">
						<image class="fengrui-img" src="../../static/down/exit.svg" mode="aspectFit"></image>
					</view>
				</view>
			</view>
		</block>
	</view>
</template>

<script>
	// 获取应用实例
	const app = getApp()
	import * as API from "../../utils/api";
	export default {
		data() {
			return {
				posdCenterID: 0,
				posUrl: '',

				// 文章详情
				wallInfo: [],
				imgUrls: [],
				title: '加载中Ing...',

				indicatorDots: true,
				statusBarHeight: 0,

				isShow: false,
				swipreIndex: 0,
				showPrivacy: false,

				// 基本配置
				wxSet: [],
				launchScene: 0, //微信小程序场景值
				// 随机数码
				code64: '',
				typeImg: '',
				// 全屏加载
				coverBulr: true,

				// 密码访问
				protected: false,
				isError: 'suss',
				getPass: '',
				public_step: false,

			}
		},
		// 分享好友配置
		onShareAppMessage(res) {
			if (res.from === 'button') { // 来自页面内分享按钮
				console.log(res.target)
			}
			return {
				title: this.title,
				imageUrl: this.wallInfo.thumbnailurl,
				path: '/pages/wall/wall?id=' + this.posdCenterID
			}
		},
		// 文章分享盆友圈 目前支持安卓
		onShareTimeline(res) {
			return {
				title: this.title,
				imageUrl: this.wallInfo.thumbnailurl,
				path: '/pages/wall/wall?id=' + this.posdCenterID
			}
		},
		onLoad(posID) {
			// 获取当前时间戳
			const now = new Date();
			const year = now.getFullYear();
			const month = now.getMonth() + 1; // 月份从 0 开始，需加 1
			const day = now.getDate();
			const postDaySum = year + month + day;
			this.postDaySum = postDaySum;

			// 接受数据
			this.posdCenterID = posID.id;
			// 接受数据
			this.posUrl = 'pages/wall/wall?id=' + posID.id;

			if (app.globalData.wxSet == '') {
				//（解决异步）
				app.on('wxSet', this.changeToken.bind(this));
			} else {
				this.wxSet = app.globalData.wxSet;
				this.statusBarHeight = app.globalData.statusBarHeight;
				this.launchScene = app.globalData.launchScene; //微信小程序场景值
				// 文章数据
				this.wallData();
			}


			// 微信分享盆友圈
			wx.showShareMenu({
				withShareTicket: true,
				menus: ['shareAppMessage', 'shareTimeline']
			})
		},
		methods: {
			//（解决异步）
			changeToken() {
				this.wxSet = app.globalData.wxSet;
				this.statusBarHeight = app.globalData.statusBarHeight;
				this.launchScene = app.globalData.launchScene; //微信小程序场景值
				// 文章数据
				this.wallData();
			},
			// 文章数据
			wallData() {
				API.getInfo([this.posdCenterID]).then((res) => {
					// console.log(res.data, 'wall')
					// 正则提取图片
					const imgRegex = /<img.*?src="([^"]*)".*?>/g;
					const imgUrls = [];
					let match;
					while ((match = imgRegex.exec(res.data.content.rendered)) !== null) {
						imgUrls.push(match[1]);
					}
					this.imgUrls = imgUrls;
					this.wallInfo = res.data;
					this.title = res.data.title.rendered;

					this.protected = res.data.content.protected; //密码访问
					this.coverBulr = false;

					if (this.wxSet.public_step != "") { //判断教程
						this.public_step = true;
					}
					if (this.protected == false) { // 广告缓存判断
						this.infoAdJudge();
					}
					this.infoPassJudge(); //密码缓存判断
				})
			},
			// 密码访问
			emitPass(pass) {
				API.getInfoPass(this.posdCenterID, pass).then((res) => {
					// console.log('文章密码详情', res.statusCode)
					if (res.statusCode != 200) {
						this.isError = 'err';
					} else {
						this.setPass(pass); //密码缓存
						// 正则提取图片
						const imgRegex = /<img.*?src="([^"]*)".*?>/g;
						const imgUrls = [];
						let match;
						while ((match = imgRegex.exec(res.data.content.rendered)) !== null) {
							imgUrls.push(match[1]);
						}
						this.imgUrls = imgUrls;
						this.wallInfo = res.data;
						this.title = res.data.title.rendered;
						this.protected = false; //密码访问
						this.infoAdJudge(); // 广告缓存判断
					}
				})
			},
			infoAdJudge() {
				// 随机数码
				if (this.wxSet.fr_copyurl == '1') {
					this.random64();
				}

				// 获取激励视频缓存
				const postAdKey = uni.getStorageSync('post_adkey');
				setTimeout(() => {
					if (this.wxSet.ad_time !== '1') {
						console.log('no启广告缓存');
						this.starpAd();
						return;
					}
					// console.log('开启广告缓存');
					// 如果postAdKey不存在，直接执行初始化广告操作，利用短路求值的逻辑或特性
					if (!postAdKey) {
						this.starpAd();
						return;
					}
					const foundItem = postAdKey.find(item => item.id === this.posdCenterID);
					// 如果foundItem不存在，直接执行初始化广告操作，利用短路求值的逻辑或特性
					if (!foundItem) {
						this.starpAd();
						return;
					}
					// 如果缓存时间不等于postDaySum，执行初始化广告操作，利用短路求值的逻辑或特性
					if (foundItem.time !== this.postDaySum) {
						this.starpAd();
						return;
					}
					// 独立文章公告弹窗情况
					if (this.wallInfoos_notice !== '') {
						uni.showModal({
							title: '公告',
							content: this.wawallInfo_notice
						});
					}
				}, 1000);
			},

			// 密码缓存判断
			infoPassJudge() {
				// 获取激励视频缓存
				const passKey = uni.getStorageSync('pass_adkey');
				// 查找缓存数据
				if (passKey) {
					const foundItem = passKey.find(item => item.id === this.posdCenterID)
					// console.log(foundItem,'查找缓存数据')
					if (foundItem) {
						if (foundItem.time == this.postDaySum) { // 缓存时间大于或等于
							// console.log(foundItem.pass,'缓存密码')
							this.getPass = foundItem.pass;
						}
					}
				}
			},
			// 初始化广告
			starpAd() {
				if (this.wxSet.wx_jili_video != '' && this.wallInfo.fr_videp_if == '1') {
					this.CreateAd();
					this.isShow = true;
				}
			},
			//初始化激励视频广告组件
			CreateAd() {
				if (this.wxSet.wx_jili_video != '') {
					if (wx.createRewardedVideoAd) {
						this.videoAd = uni.createRewardedVideoAd({
							adUnitId: this.wxSet.wx_jili_video
						})
						this.videoAd.onLoad(() => {})
						this.videoAd.onError((err) => {
							console.log(err)
							// 播放错误下发奖励
							this.downWall();
							// 播放错误下发奖励
							wx.showToast({
								icon: 'none',
								title: "错误码：" + err.errCode
							})
							this.isShow = false;
						})
						this.videoAd.onClose((res) => {
							if (res && res.isEnded) {
								uni.showToast({
									icon: 'none',
									title: "感谢您的支持"
								})
								this.isShow = false;
								this.downWall();

								// 设置广告缓存
								if (this.wxSet.ad_time == '1') {
									this.setRead();
								}
							} else {
								uni.showToast({
									icon: 'none',
									title: "中途关闭广告"
								})
							}
						})
					}

				}
			},
			// 获取滚动区域index
			bindChange(e) {
				this.swipreIndex = e.detail.current;
			},
			// 判断用户是否授权"保存到相册"
			sevePhto(e) {
				if (this.launchScene == 1154) {
					uni.showToast({
						title: '请前往小程序使用完整服务',
						icon: "none"
					})
					return;
				}

				this.typeImg = e; //壁纸点击类型
				//  保存图片
				if (this.isShow == true) {
					this.adDown();
				} else {
					this.downWall();
				}
			},
			// 点击解锁
			adDown() {
				uni.showModal({
					title: '提示',
					content: '看广告保存壁纸到相册',
					success: (res) => {
						if (res.confirm) {
							this.getVideoAd();
						}
					}
				})
			},

			// 激励视频
			getVideoAd: function() {
				let that = this;
				// 用户触发广告后，判断设备信息，非手机端不显示广告，若是手机端显示激励视频广告
				wx.getSystemInfo({
					success: (res) => {
						if (res.model.includes == 'ipad') {
							wx.showToast({
								icon: 'error',
								title: "请使用移动端设备访问"
							})
						} else {
							if (that.videoAd) {
								that.videoAd.show().catch(() => {
									// 失败重试
									that.videoAd.load()
										.then(() => that.videoAd.show())
										.catch(err => {
											console.log('激励视频 广告显示失败', err)
										})
								})
							}
						}
					}
				})
			},

			// 下载媒体文件
			downWall(e) {
				if (this.wallInfo.pos_read == '5') {
					if (this.typeImg == 'img') { //判断是下载单个，还是打包下载
						const imageUrl = this.imgUrls[this.swipreIndex]; // 当前要下载的图片
						uni.showLoading({
							title: '下载中...',
						});
						uni.downloadFile({
							url: imageUrl,
							success: (res) => {
								uni.hideLoading();
								if (res.statusCode === 200) {
									const tempFilePath = res.tempFilePath;
									this.saveImage(tempFilePath);
								} else {
									uni.showToast({
										title: '图片/视频下载失败',
										icon: 'none',
									});
								}
							},
							fail: (err) => {
								console.error('图片下载失败:', err);
								uni.showToast({
									title: '图片下载失败',
									icon: 'none',
								});
							},
						});
					} else {
						this.showPrivacy = true; // 弹窗
					}
				} else {
					uni.navigateTo({
						url: '../weblist/weblist?url=' + encodeURIComponent(JSON.stringify(this.wallInfo.redbag)) +
							'&type=json',
					})
				}

			},

			// 保存图片相册
			saveImage(tempFilePath) {
				uni.saveImageToPhotosAlbum({
					filePath: tempFilePath,
					success: () => {
						uni.showToast({
							title: '图片保存成功',
							icon: 'success',
						});
					},
					fail: (err) => {
						console.error('图片保存失败:', err);
						uni.showToast({
							title: '图片保存失败',
							icon: 'none',
						});
					},
				});
			},

			// 视频图片相册
			saveVideo(tempFilePath) {
				uni.saveVideoToPhotosAlbum({
					filePath: tempFilePath,
					success: () => {
						uni.showToast({
							title: '图片保存成功',
							icon: 'success',
						});
					},
					fail: (err) => {
						console.error('图片保存失败:', err);
						uni.showToast({
							title: '图片保存失败',
							icon: 'none',
						});
					},
				});
			},
			// 设置密码缓存
			setPass(e) {
				var passKey = uni.getStorageSync('pass_adkey');
				if (passKey == '') {
					var passKey = [];
				}

				// 检测事否存在ID
				var isItem = passKey.find(item => item.id === this.posdCenterID);
				// 如果有更新ID,若没有新增ID
				if (isItem) {
					const updateData = (id, newData) => {
						passKey = passKey.map(item => {
							if (item.id === id) {
								return {
									...item,
									...newData
								};
							}
							return item;
						});
					};
					updateData(this.posdCenterID, {
						time: this.postDaySum,
					});
				} else {
					var jlis = passKey.unshift({
						id: this.posdCenterID,
						time: this.postDaySum,
						pass: e,
					})
				}
				uni.setStorageSync('pass_adkey', passKey);
				// console.log(passKey)
			},

			// 返回按钮 建立页面栈 如果是1则是分享打开需要返回主页，大于1则返回上一级
			tarBlack: function() {
				var selPage = getCurrentPages();
				if (selPage.length == 1) {
					uni.switchTab({
						url: '../index/index',
					})
				} else {
					uni.navigateBack({
						delta: 1
					});
				}
			},
			// 关闭弹窗
			noPrivacy() {
				this.showPrivacy = false;
			},
			// 随机数码
			random64() {
				let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
				let randomString = '';
				for (let i = 0; i < 64; i++) {
					let randomIndex = Math.floor(Math.random() * characters.length);
					randomString += characters.charAt(randomIndex);
				}
				this.code64 = randomString;
				// console.log('随机吗', randomString)
			},
			// 设置广告缓存
			setRead() {
				var postAdKey = uni.getStorageSync('post_adkey');
				if (postAdKey == '') {
					var postAdKey = [];
				}

				// 检测事否存在ID
				var isItem = postAdKey.find(item => item.id === this.posdCenterID);
				// 如果有更新ID,若没有新增ID
				if (isItem) {
					const updateData = (id, newData) => {
						postAdKey = postAdKey.map(item => {
							if (item.id === id) {
								return {
									...item,
									...newData
								};
							}
							return item;
						});
					};
					updateData(this.posdCenterID, {
						time: this.postDaySum,
					});
				} else {
					var jlis = postAdKey.unshift({
						id: this.posdCenterID,
						time: this.postDaySum,
					})
				}
				uni.setStorageSync('post_adkey', postAdKey);
				// console.log(postAdKey)
			},
			// 复制Url
			tapDownUrl(e) {
				uni.setClipboardData({
					data: e,
				})
			}
		},
	}
</script>

<style>
	/* 弹窗 */
	.privac-x {
		height: 80rpx;
		width: 80rpx;
		position: absolute;
		right: 4%;
		top: 5%;
		z-index: 999;
	}

	.privacy-bg {
		position: fixed;
		top: 0;
		left: 0;
		height: 100%;
		width: 100%;
		background: rgba(0, 0, 0, .5);
		z-index: 9999999;
	}

	.privacy-view {
		position: absolute;
		animation: mymove 0.6s infinite;
		animation-iteration-count: 1;
		animation-fill-mode: forwards;
		left: 50%;
		transform: translate(-50%, 0%);
		width: 85%;
		padding: 40rpx;
		background-color: #ffffff;
		border-radius: 40rpx;
	}

	.privacy-title {
		margin: 40rpx auto;
		text-align: center;
		font-size: 36rpx;
		font-weight: bold;
	}


	.privac-text {
		background-color: #F2F2F2;
		color: #ADADAD;
		padding: 30rpx;
		font-size: 26rpx;
		margin: 14rpx;
		border-radius: 20rpx;
		text-align: justify;
	}

	.privacy-link {
		color: #07c160;
		line-height: 40rpx;
	}

	.privac-btn {
		background-color: black;
		color: #ffffff;
		width: 80%;
		text-align: center;
		border-radius: 100rpx;
		margin: 30rpx 10%;
		padding: 15rpx;
	}

	.privac-no {
		text-align: center;
		margin-top: 30rpx;
		color: #666;
		font-size: 26rpx;
	}

	@keyframes mymove {
		from {
			bottom: -20%;
		}

		to {
			bottom: 4%;
		}
	}

	/* 背景颜色 */
	.wall-bg-left {
		opacity: 1;
		background: #99C2FF;
		filter: blur(360rpx);
		position: absolute;
		left: -40rpx;
		bottom: 200rpx;
		width: 480rpx;
		height: 480rpx;
	}

	.wall-bg-right {
		position: absolute;
		right: -40rpx;
		top: 100rpx;
		width: 480rpx;
		height: 480rpx;
		opacity: 1;
		background: #FF9999;
		filter: blur(360rpx);
	}

	/* 下载组建 */
	.wall-flex {
		display: flex;
		align-items: center;
		justify-content: space-around;
		width: 100%;
		position: fixed;
		bottom: 60rpx;
		left: 0;
	}

	.wall-share {
		background: rgba(255, 202, 58, 0.2);
	}

	.wall-down {
		background: rgba(58, 104, 255, 0.2);
	}

	.wall-url {
		background: rgba(255, 58, 153, 0.2);
	}

	.wall-radus {
		height: 120rpx;
		width: 120rpx;
		border-radius: 200rpx;
		position: relative;
	}

	.wall-radus-img {
		height: 70rpx;
		width: 70rpx;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	.wall-radus-font {
		font-size: 28rpx;
		margin-top: 20rpx;
		text-align: center;
	}

	/* .案例区 */
	.swiper-h {
		margin-top: 50rpx;
		padding: 36rpx;
	}

	.swiper-title {
		font-size: 60rpx;
		font-weight: bold;
	}

	.swiper-desrc {
		margin: 40rpx auto;
		font-size: 26rpx;
	}

	.swiper-wall {
		height: 70%;
		width: 100%;
		top: 12%;
		left: 0;
		position: absolute;
		z-index: 2;
	}


	.swiper-wall-list-img {
		height: 100%;
		width: 100%;
		overflow: hidden;
		margin: auto;
		position: relative;
		border-radius: 60rpx;
	}

	.swiper-wall-item {
		height: 100%;
		width: 90% !important;
		padding: 0 5%;
	}

	.wallcover-fixed {
		position: fixed;
		bottom: 40rpx;
		width: 100%;
		overflow: hidden;
	}

	.wallcover-title {
		margin: 36rpx;
		text-align: center;
		font-weight: bold;
	}

	.wallcover-title-desrc {
		margin: 0 36rpx;
		color: #ADADAD;
		font-size: 26rpx;
	}

	.wallcover-flex {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		margin-top: 40rpx;
	}

	.fengrui-img-wall {
		height: 100%;
		width: 100%;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		border-radius: 60rpx;
	}

	.wallcover-btn {
		background-color: #fff4e0 !important;
		color: #fec009 !important;
	}

	.wall-video {
		height: 100%;
		width: 100%;
	}

	.wall-video-cover {
		border-radius: 60rpx;
		overflow: hidden;
		width: 100%;
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
	}

	.detail-btn {
		width: 44% !important;
		margin: 0rpx auto 30rpx auto;
	}

	/* .自定义状态栏 */
	.nav-view {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
	}

	.nav-icon {
		height: 70rpx;
		width: 70rpx;
		margin-left: 30rpx;
	}

	/* 全局 */
	page,
	.centem-body {
		width: 100%;
		height: 100%;
	}

	button {
		background-color: unset !important;
	}

	button:after {
		border: 0px solid rgba(0, 0, 0, .2);

	}

	/* 暗黑模式下应用的样式 */
	@media (prefers-color-scheme: dark) {
		.privacy-view {
			background: #161616;
		}

		.privac-text {
			background: #202020;
		}
	}
</style>